package com.beiding.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.session.ConcurrentSessionControlAuthenticationStrategy;
import org.springframework.session.data.redis.RedisOperationsSessionRepository;
import org.springframework.session.security.SpringSessionBackedSessionRegistry;

@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {



    //基于Redis的Session注册表
    private SpringSessionBackedSessionRegistry sessionRegistry;

    //基于Redis的Session仓库
    private RedisOperationsSessionRepository repository;

    @Autowired
    public void setRepository(RedisOperationsSessionRepository repository) {
        this.repository = repository;
        sessionRegistry = new SpringSessionBackedSessionRegistry<>(repository);

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .permitAll()
                .and().headers().frameOptions().sameOrigin()
                .and().csrf().disable();


        http.sessionManagement()
                .sessionAuthenticationStrategy(new ConcurrentSessionControlAuthenticationStrategy(
                        sessionRegistry
                ))
                .invalidSessionUrl("/login")
                .maximumSessions(1)
                .sessionRegistry(sessionRegistry)
                .expiredUrl("/login");


    }





}
